@extends('layouts.back_stage')
@section('content')
    <style>
        .addCode{float:right;margin-right:30px;}

        .tableBg{padding:30px;background:#fff;}

        .input-item{width:200px;padding-right: 0;margin:20px 10px 20px 0;}
        .timeDuan{margin:20px 0;}
        .input-time{width:220px;margin-right:10px;}
        .pagination-box{text-align: center;box-sizing:border-box;margin-top:20px;}
        .el-range-editor--small.el-input__inner{width:300px;}
        .el-date-editor .el-range-separator{padding:0 15px}
        .el-textarea{width:400px;}
        ::-webkit-scrollbar {height: 8px;}
        .el-select .el-input .el-select__caret.el-input__icon{line-height:22px;}
        .el-table--mini.opTb th{padding:0;}

        .tb-edit .el-input {display: none}
        .tb-edit .current-row .el-input {display: block}
        .tb-edit .current-row .el-input+span {display: none}
        .tb-edit .el-input--small .el-input__inner{line-height:22px;height:22px;}

        .el-table tr:hover>td{background:initial !important;}
        .el-table tr.current-row>td{background:initial !important;}
        .el-table .success-row {background: #ecf5ff !important;}
        .el-table__header tr>th {background: #f8f8f8 !important;}
        .el-checkbox__input.is-checked .el-checkbox__inner {background-color: #dcdfe6;border-color: #dcdfe6;}
        .el-checkbox__input.is-focus .el-checkbox__inner {background-color: #dcdfe6;border-color: #dcdfe6;}
        [v-cloak] {display: none;}
    </style>

    <div class="container">
        <div style="padding:20px 20px 20px 0;overflow:hidden;"><h3 style="float:left;">配发详情</h3></div>
        <!-- 主体-->
        <div class="page-body">
            <div class="row app" id="shopInfos" v-cloak>
                <div class="col-md-12 row row-table-box">
                    <div style="width:100%;height:auto;float:left;background:#fff;">
                        <div class="tableBg" style="margin-top:10px;">
                            <el-table :data="oneTB" class="tb-edit" size="mini" border style="margin-top:20px;" highlight-current-row
                                      @row-click="rowClick"
                                      :span-method="objectSpanMethod1"
                                      :row-class-name="tableRowClassName"
                                      @cell-mouse-leave="cellMouseLeave"
                                      @cell-mouse-enter="cellMouseEnter"
                                       >
                                <el-table-column prop="girard" label="款号" min-width="90" :resizable='false'></el-table-column>
                                <el-table-column prop="color" label="颜色" min-width="70" :resizable='false'></el-table-column>
                                <el-table-column prop="type" label="类别" min-width="90" :resizable='false'></el-table-column>

                                <el-table-column v-for="(item,index) in sizeGr"  :label="item.key76" width="70" :resizable='false'>
                                    <el-table-column :label="item.key75" width="70" :resizable='false'>
                                        <el-table-column :label="item.key79" width="70" :resizable='false'>
                                            <el-table-column :label="item.key154" width="70" :resizable='false'>
                                                <el-table-column :label="item.key146" width="70" :resizable='false'>
                                                    <el-table-column :label="item.key161" width="70" :resizable='false'>
                                                        <el-table-column :label="item.key77" width="70" :resizable='false'>
                                                            <el-table-column :prop="item.key_0" :label="item.key140" width="70" :resizable='false'>
                                                                <template slot-scope="scope">
                                                                    <span v-if="item.key_0==='size_group'">@{{scope["row"][item["key_0"]] }}</span>
                                                                    <span v-else>
                                                                        <span v-if="index<=scope.row.num.length">@{{ getMasterNums(scope) }}</span>
                                                                    </span>
                                                                </template>
                                                            </el-table-column>
                                                        </el-table-column>
                                                    </el-table-column>
                                                </el-table-column>
                                            </el-table-column>
                                        </el-table-column>
                                    </el-table-column>
                                </el-table-column>

                                <el-table-column prop="count" label="合计/件" width="70" :resizable='false'>
                                    <template slot-scope="scope">
                                        <span>@{{ totalCount(scope) }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="price" label="吊牌价/元" align="right" width="120" :resizable='false'></el-table-column>
                                <el-table-column prop="cardCount" label="吊牌金额/元" align="right" width="150" :resizable='false'>
                                    <template slot-scope="scope">
                                        <span>@{{ diaoCount(scope) }}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                            {{--<br>数据:@{{oneTB}}--}}
                        </div>

                        <div class="tableBg" style="margin-top:10px;margin-top:30px;">
                            <el-table :data="twoTB" class="tb-edit" size="mini" border style="margin-top:20px;" highlight-current-row :span-method="objectSpanMethod2">
                                <el-table-column prop="girard" label="款号" min-width="90" :resizable='false'></el-table-column>
                                <el-table-column prop="color" label="颜色" min-width="70" :resizable='false'></el-table-column>
                                <el-table-column prop="client_name" label="客户" min-width="100" :resizable='false'></el-table-column>
                                <el-table-column prop="type" label="类别" min-width="90" :resizable='false'></el-table-column>
                                <el-table-column prop="loseSize" label="缺码数" width="50" :resizable='false'>
                                    <template slot-scope="scope">
                                        <span>@{{ getMissing(scope) }}</span>
                                    </template>
                                </el-table-column>

                                <el-table-column v-for="(item,index) in sizeGr"  :label="item.key76" width="70" :resizable='false'>
                                    <el-table-column :label="item.key75" width="70" :resizable='false'>
                                        <el-table-column :label="item.key79" width="70" :resizable='false'>
                                            <el-table-column :label="item.key154" width="70" :resizable='false'>
                                                <el-table-column :label="item.key146" width="70" :resizable='false'>
                                                    <el-table-column :label="item.key161" width="70" :resizable='false'>
                                                        <el-table-column :label="item.key77" width="70" :resizable='false'>
                                                            <el-table-column :prop="item.key_0" :label="item.key140" width="70" :resizable='false'>
                                                                <template slot-scope="scope">
                                                                    <span v-if="item.key_0==='size_group'">@{{scope["row"][item["key_0"]] }}</span>
                                                                    <span v-else>
                                                                        <span v-if="scope.row.type==='已分配数'">
                                                                            <span v-if="index<=scope.row.num.length">
                                                                            <el-input size="small" v-model="scope['row']['num'][index-1]" @keyup.native="handleEdit(scope['row']['num'][index-1],scope)"></el-input>
                                                                            <span>@{{scope['row']['num'][index-1]}}</span>
                                                                        </span>
                                                                        </span>
                                                                        <span v-else-if="scope.row.type=='订单欠数'">
                                                                            <span v-if="index<=scope.row.num.length">@{{getChildOwn(scope)}}</span>
                                                                       </span>
                                                                    </span>
                                                                </template>
                                                            </el-table-column>
                                                        </el-table-column>
                                                    </el-table-column>
                                                </el-table-column>
                                            </el-table-column>
                                        </el-table-column>
                                    </el-table-column>
                                </el-table-column>

                                <el-table-column prop="count" label="合计/件" width="70" :resizable='false'>
                                    <template slot-scope="scope">
                                        <span>@{{ totalCount(scope) }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="price" label="吊牌价/元" align="right" width="120" :resizable='false'></el-table-column>
                                <el-table-column prop="cardCount" label="吊牌金额/元" align="right" width="150" :resizable='false'>
                                    <template slot-scope="scope">
                                        <span>@{{ diaoCount(scope) }}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                            {{--<br>数据:@{{twoTB}}--}}
                        </div>
                        <el-button class="addCode" type="primary" size="small" @click="saveInfo">保存</el-button>
                    </div>
                </div>
            </div>
        </div>
        <!-- /主体-->
    </div>
    <script>
        new Vue({
            el: '#shopInfos',
            data:{
                sizeGr:[],//尺码数据

                oneTB:[], //一级数据
                twoTB:[],//二级数据
                json:[],//存储数据
                vals:0,//储存数字和


                //储存链接数据
                sale_season_id:'',//销售季节
                brand_id:'',//品牌
                factory_id:'',//仓库
                is_modify:'',//发货查看

                /*鼠标滑过背景颜色*/
                rowIndex: '-1',
                OrderIndexArr: [],
                hoverOrderArr: [],
            },
            mounted(){
                this.getHref();
                this.common();
                this.grabble();
                this.getOrderNumber();
            },
            computed: { //计算属性
                //合计
                totalCount() {
                    return function(scope){
                        let cvs=0;
                        let scpArr=scope.row.num;
                        for(var cv=0;cv<scpArr.length;cv++){
                            if(scpArr[cv]==''){
                                scpArr[cv]=0;
                            }
                            cvs+=Number(scpArr[cv]);
                        }
                        scope.row.count=cvs;
                        return cvs
                    }
                },
                //吊牌总额
                diaoCount(){
                    return function(scope){
                        let scpArr=scope.row.num;//数量
                        let count=scope.row.count;//合计
                        let money=scope.row.price;//吊牌价
                        let oneNum=0;
                        let twoNum=0;
                        if(scpArr.length==9 && money.indexOf("/")!=-1) {
                            for (var cc = 0; cc < scpArr.length; cc++) {
                                if (scpArr[cc] == '') {
                                    scpArr[cc] = 0;
                                }
                                if (cc < 7) {
                                    oneNum += Number(scpArr[cc]);
                                } else {
                                    twoNum += Number(scpArr[cc]);
                                }
                            }
                        }
                        if(money.indexOf("/")!=-1){
                            let priArr=money.split("/");
                            let disOne=priArr[0]*oneNum;
                            let disTwo=priArr[1]*twoNum;
                            return (disOne+disTwo).toFixed(2);
                        }else{
                            return (money*count).toFixed(2);
                        }
                    }
                },
                //缺码数
                getMissing(){
                    return function(scope){
                        let count = 0;
                        for(let value of scope.row.num){
                            if(value == 0 || value == ''){
                                count ++
                            }
                        }
                        return count
                    }
                },
                //可用库存，已分配数,订单需求
                getMasterNums(){
                    return function(scope){
                        let num_index = scope.column.property.replace(/[^0-9]/ig,"");
                        if(scope.row.type == '可用库存'){
                            let child_1 = 0;
                            let sameData = this.twoTB.filter((n) =>n.index == scope.row.index && n.type == '已分配数');
                            for(let value of sameData){
                                child_1 += Number(value.num[num_index])
                            }
                            scope.row.num[num_index] = scope.row.bak_nums[num_index] - child_1;
                            return scope.row.bak_nums[num_index] - child_1
                        }else if(scope.row.type == '订单已分配'){
                            let child = 0;
                            let child_data = scope.row.child.filter((n)=>n.index == scope.row.index && n.type == '已分配数');
                            for(let value of child_data){
                                child += Number(value.num[num_index])
                            }
                            scope.row.num[num_index] = child;
                            return child
                        }else if(scope.row.type == '订单需求'){
                            let num_index = scope.column.property.replace(/[^0-9]/ig,"");
                            let child = 0;
                            let sameData = this.twoTB.filter((n) =>n.index == scope.row.index && n.type == '已分配数');
                            for(let value of sameData){
                                child += Number(value.num[num_index])
                            }
                            scope.row.num[num_index] = scope.row.bak_nums[num_index] - child;
                            return scope.row.bak_nums[num_index] - child
                        }
                    }
                },
                //订单欠数
                getChildOwn(){
                    return function(scope){
                        let sameData = this.twoTB.find((n) => n.loop == scope.row.loop && n.type == '已分配数');
                        let num_index = scope.column.property.replace(/[^0-9]/ig,"");
                        let order_own = scope.row.bak_nums[num_index];
                        let order_dis = sameData.num[num_index];
                        scope.row.num[num_index] = Number(order_own) - Number(order_dis);
                        return Number(order_own) - Number(order_dis);
                    }
                },
            },
            methods:{
                /*获取链接数据*/
                getHref(){
                    let href=window.location.href;
                    let str1=href.split("?")[1];
                    let strArr1=str1.split("&");
                    this.sale_season_id=strArr1[0].split("=")[1];
                    this.brand_id=strArr1[1].split("=")[1];
                    this.factory_id=strArr1[2].split("=")[1];
                    this.is_modify=strArr1[3].split("=")[1];
                },
                /*尺码数据*/
                common(){
                    var that=this;
                    $.ajax({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
                        },
                        type: 'post',
                        url: '/distribution/sizeGroupHead',
                        data: {
                            type:1,
                        },
                        success: function (data) {
                            //console.log(data);
                            if(data.result.success){
                                that.sizeGr=data.content.vertical;
                            }else{
                                that.$notify.error({
                                    title: '提示',
                                    message: data.result.errorMsg,
                                });
                            }
                        }
                    });
                },
                //获取数据
                grabble(){
                    var that=this;
                    $.ajax({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
                        },
                        type: 'post',
                        url: '/allotment-manager/client-order-distribute',
                        data: {
                            id:'{{$id}}',
                            factory_type:this.factory_id,
                        },
                        success: function (data) {
                            //console.log(data);
                            if(data.result.success){
                                that.oneTB=data.content;
                                for(let value of data.content){
                                    value['bak_nums'] = [...value.num]
                                    if(value.type == '可用库存'){
                                        for(let data of value.child){
                                            data['bak_nums'] = [...data.num]
                                        }
                                        let sameData = data.content.filter((n)=> n.index == value.index && n.type != '可用库存')
                                        for(let data of sameData){
                                            data['child'] = value.child
                                        }
                                    }
                                }
                                //合并行鼠标滑过背景显示
                                var OrderObj = {};
                                that.oneTB.forEach(function (element, index) {
                                    element.rowIndex = index;
                                    if (OrderObj[element.index]) {
                                        OrderObj[element.index].push(index)
                                    } else {
                                        OrderObj[element.index] = [];
                                        OrderObj[element.index].push(index)
                                    }
                                }, this);

                                for (var k in OrderObj) {
                                    if (OrderObj[k].length > 1) {
                                        that.OrderIndexArr.push(OrderObj[k])
                                    }
                                }
                                //console.log(that.OrderIndexArr)
                            }else{
                                that.$notify.error({
                                    title: '提示',
                                    message: data.result.errorMsg,
                                });
                            }
                        }
                    });
                },

                /*点击出详情*/
                rowClick(row, event, column) {
                    var that=this;
                    /*当事件源是a的时候，我们不展开*/
                    let nodeName = event.target.nodeName;
                    if(nodeName==='BUTTON'){
                        return;
                    }
                    if(nodeName==='SPAN'){
                        return;
                    }
                    this.twoTB = row.child;
                },
                /*按下*/
                handleEdit(val,scope) {
                    let num_index = scope.column.property.replace(/[^0-9]/ig,"");
                    //已分配合计
                    let sameVal = this.twoTB.filter((n) =>n.index == scope.row.index && n.type == '已分配数');
                    let val_1 = 0;
                    for(let value of sameVal){
                        val_1 += Number(value.num[num_index])
                    }
                    //console.log(val_1)

                    //可用库存
                    let kuData = this.oneTB.filter((n) =>n.index == scope.row.index && n.type == '可用库存');
                    let kuNum = kuData[0].bak_nums[num_index];

                    //订单需求
                    let xuData = this.oneTB.filter((n) =>n.index == scope.row.index && n.type == '订单需求');
                    let xuNum = xuData[0].bak_nums[num_index];

                    //订单欠数
                    let qianData = this.twoTB.filter((n) =>n.index == scope.row.index && n.type == '订单欠数');
                    let qianNum = qianData[0].bak_nums[num_index];

                    if(Number(kuNum)-Number(val_1)<0 ){
                        this.$notify.error({
                            title: '提示',
                            message: "已分配不能大于可用库存",
                        });
                        scope.row.num[num_index] = 0;
                        this.$set(this.twoTB,scope.$index,scope.row);
                        return false;
                    }
                    if(Number(xuNum)-Number(val_1)<0){
                        this.$notify.error({
                            title: '提示',
                            message: "已分配不能大于订单需求",
                        });
                        scope.row.num[num_index] = 0;
                        this.$set(this.twoTB,scope.$index,scope.row);
                        return false;
                    }
                    if(Number(qianNum)-Number(val_1)<0){
                        this.$notify.error({
                            title: '提示',
                            message: "已分配不能大于订单欠数",
                        });
                        scope.row.num[num_index] = 0;
                        this.$set(this.twoTB,scope.$index,scope.row);
                        return false;
                    }
                    var reg=/^([1-9]\d*|[0]{1,1})$/;
                    if(!reg.test(val)){
                        this.$notify.error({
                            title: '提示',
                            message: "请填写大于等于0的正整数",
                        });
                        scope.row.num[num_index] = 0;
                        this.$set(this.twoTB,scope.$index,scope.row);
                        return false;
                    }
                },
                /*保存*/
                saveInfo(){
                    var that=this;
                    let json=[];
                    let res = this.oneTB.filter((n) => n.type == '可用库存');
                    for(let value of res){
                        for(let str of value.child){
                            if(str.type=='已分配数'){
                                json.push(str);
                            }
                        }
                    }
                    let dat=[];
                    for(let h of json){
                        dat.push({girard:h.girard,color:h.color,client_id:h.client_id,num:h.num,size:h.size});
                    }
                    $.ajax({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
                        },
                        type: 'post',
                        url: '/allotment-manager/order-transfer-wholesale',
                        data: {
                            id:'{{$id}}',
                            factory_type:that.factory_id,
                            data:JSON.stringify(dat),
                            sale_season_id:that.sale_season_id,
                            brand_id:that.brand_id,
                        },
                        success: function (data) {
                            //console.log(data);
                            if(data.result.success){
                                that.$notify.success({
                                    title: '提示',
                                    message: "操作成功"
                                });
                                window.location.href='/allotment-manager/order-allotment';
                            }else{
                                that.$notify.error({
                                    title: '错误',
                                    message: data.result.errorMsg
                                });
                            }
                        }
                    })
                },
                /*一级合并*/
                objectSpanMethod1({ row, column, rowIndex, columnIndex }) {
                    if (columnIndex ===  0 || columnIndex ===  1) {
                        // 合并第一列
                        if (rowIndex % 3 === 0) {
                            // 从第一行开始
                            return {
                                rowspan: 3,//行
                                colspan: 1 //列
                            };
                        } else {
                            return {
                                rowspan: 0,
                                colspan: 0
                            };
                        }
                    }
                },
                /*二级合并*/
                objectSpanMethod2({ row, column, rowIndex, columnIndex }) {
                    if (columnIndex ===  0 || columnIndex ===  1 || columnIndex ===  2) {
                        // 合并第一列
                        if (rowIndex % 2 === 0) {
                            // 从第一行开始
                            return {
                                rowspan: 2,//行
                                colspan: 1 //列
                            };
                        } else {
                            return {
                                rowspan: 0,
                                colspan: 0
                            };
                        }
                    }
                },
                /*二级合并*/
                objectSpanMethod2({ row, column, rowIndex, columnIndex }) {
                    if (columnIndex ===  0 || columnIndex ===  1 || columnIndex ===  2) {
                        // 合并第一列
                        if (rowIndex % 2 === 0) {
                            // 从第一行开始
                            return {
                                rowspan: 2,//行
                                colspan: 1 //列
                            };
                        } else {
                            return {
                                rowspan: 0,
                                colspan: 0
                            };
                        }
                    }
                },
                //合并行鼠标滑过背景显示
                getOrderNumber: function () {
//                    console.log(this.oneTB)
//			        var OrderObj = {};
//			        this.oneTB.forEach(function (element, index) {
//			          	element.rowIndex = index;
//			          	if (OrderObj[element.id]) {
//			            		OrderObj[element.id].push(index)
//			          	} else {
//			            		OrderObj[element.id] = [];
//			            		OrderObj[element.id].push(index)
//			          	}
//			        }, this);
//
//			        for (var k in OrderObj) {
//			        		if (OrderObj[k].length > 1) {
//			            		this.OrderIndexArr.push(OrderObj[k])
//			          	}
//			        }
//			        console.log(this.OrderIndexArr)
			   },
                tableRowClassName: function ({row,rowIndex}) {
      				var arr = this.hoverOrderArr;
      				for (var i = 0; i < arr.length; i++) {
        				if (rowIndex == arr[i]) {
          					return 'success-row'
        				}
      				}
                },
                cellMouseEnter: function (row, column, cell, event) {
                     this.rowIndex = row.rowIndex;
                     this.hoverOrderArr = [];
                     this.OrderIndexArr.forEach(function (element) {
                         if (element.indexOf(this.rowIndex) >= 0) {
                                this.hoverOrderArr = element
                         }
                     }, this);
                     //console.log(this.hoverOrderArr)
                },
                cellMouseLeave: function (row, column, cell, event) {
                     this.rowIndex = '-1'
                }
            }
        });
//        $(document).on("click",".el-table .success-row",function(){
//            $(this).css({"background":"#ecf5ff"});
//            $(this).siblings({"background":"#fff"});
//        })
    </script>
@endsection
